<?php

/**
 * @see Zend_Auth_Adapter_Interface
 */
require_once 'Zend/Auth/Adapter/Interface.php';


/**
 * A Zend_Auth Authentication Adapter allowing the use of OAuth protocol for authentication.
 *
 * @category   Core
 * @package    Core_Auth
 * @subpackage Core_Auth_Adapter
 */
class Core_Auth_Adapter_OAuth implements Zend_Auth_Adapter_Interface
{
	/**
	 * OAuth Configuration Options.
	 * 
	 * @var array
	 */
	private $options;
	
    /**
     * Constructor
     *
     * @param  array|Zend_Config $options
     * @param string $redirectUri the URI to redirect the user to after successful authentication
     */
    public function __construct( $options )
    {
    	$this->options = $options;
    }

    /**
     * Authenticates the user against facebook
     * Defined by Zend_Auth_Adapter_Interface.
     *
     * @throws Zend_Auth_Adapter_Exception If answering the authentication query is impossible
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
    	// Get the request object.
    	$frontController = Zend_Controller_Front::getInstance();
    	$request = $frontController->getRequest();
    	$params = $request->getParams();
    	
    	// Configure the OAuth Consumer
    	$consumer = new Zend_Oauth_Consumer( $this->options );
		
    	// Pull a temporary session storage box for the request token.
    	$session = new Zend_Session_Namespace( 'OAUTH_TOKENS' );
		
    	// First of all, switch out if we have a token or not.
    	if ( !empty($session->requestToken) && !empty($params['oauth_token']))
    	{
    		$accessToken = $consumer->getAccessToken ( $params, $session->requestToken );
    		$requestToken = $session->requestToken;
    		$session->unsetAll();
    		
    		// We're returning the actual access token, since different providers may send different additional parameters.
    		$messages = array('token' => $accessToken);
    		$id = $accessToken->getToken();
    		
            return new Zend_Auth_Result( Zend_Auth_Result::SUCCESS, $id, $messages );
    	}
    	else
    	{
    		$session->unsetAll();
    		$token = $consumer->getRequestToken();
    		$session->requestToken = $token;
    		$consumer->redirect();
	        return new Zend_Auth_Result( Zend_Auth_Result::FAILURE, null, 'Invalid token!' );
    	}
    	
        return new Zend_Auth_Result( Zend_Auth_Result::FAILURE, null, 'Something went wrong!' );
    }
}
